/**
 * Copyright (c) 2014-2018, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.javaguide;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数组队列.
 *
 * @author Xue Xue (xuexue1@huli.com)
 * @version $Id$
 * @since 2020/1/16
 */
public class ListMain {

    /**
     * 使用集合的修改方法:add()、remove()、clear()会抛出异常;
     * 虽然传入的是个数组，转化成的List其实是Arrays的一个内部类，如Test1中的方法并没实现.
     */
    public static void arraysTest1() {
        List a = Arrays.asList(1, 2, 3);
        a.add(4);
    }

    /**
     * 并且，低层其实还是数组，如果修改了数组的值，list.get()的值也会随之改变.
     */
    public static void arraysTest2() {
        Integer a[] = new Integer[]{1, 2, 3};
        List list = Arrays.asList(a);
        System.out.println(list.get(0));
        a[0] = 4;
        System.out.println(list.get(0));
    }

    /**
     * asList传入必须是对象,这种int a[]基础类型传入的话;
     * 会把整个数组当做一个对象,得到一个list.size=1 && list.get(0)=a[]的数组.
     */
    public static void arraysTest3() {
        int a[] = {1, 2, 3};
        List list = Arrays.asList(a);
        System.out.println(JSON.toJSONString(list.get(0)));
    }

    /**
     * 如何将数组输出成正常的ArrayList.
     */
    public static void arraysTest4() {
        Integer a[] = {1, 2, 3};
        //手动实现.
        byHand(a);
        //最简洁.
        byConstructor(a);
        //java8.
        byJava8();
        //byGuava
        byGuava(a);
    }

    public static void arraysTest5() {
        Integer a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        List<Integer> list = Arrays.asList(a);
        Collections.reverse(list);
        System.out.println(JSON.toJSONString(list));
    }

    public static <T> List<T> byHand(T[] a) {
        ArrayList b = new ArrayList(a.length);
        for (T c : a) {
            b.add(c);
        }
        return b;
    }

    public static <T> List<T> byConstructor(T[] a) {
        return new ArrayList<>(Arrays.asList(a));
    }

    public static <T> List<T> byGuava(T[] a) {
        //对于不可变集合
        List b = ImmutableList.copyOf(a);
        //可变集合
        List c = Lists.newArrayList(a);
        return c;
    }

    public static void byJava8() {
        Integer a[] = {1, 2, 3};
        List b = Arrays.stream(a).collect(Collectors.toList());
        //非包装类型的数组需要boxed一下.
        int c[] = {1, 2, 3};
        List d = Arrays.stream(c).boxed().collect(Collectors.toList());
    }


    public static void main(String[] args) {
//        arraysTest1();
//        arraysTest2();
//        arraysTest3();
        arraysTest5();

//       int a= new Scanner(System.in).nextInt();
//       System.out.println(a>>1);
    }
}
